package com.kangtushizhe.utils;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.kangtushizhe.entities.CommonResult;
import io.jsonwebtoken.*;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {

    @Value("${jwt.secretKey}")
    private String secretKey;
    @Value("${jwt.issue}")
    private String issue;


    public CommonResult createJWT(String id, String subject, long ttlMillis, Map<String, Object> info) throws Exception {
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(new Date()) // 发行时间
                .signWith(SignatureAlgorithm.HS256, secretKey) // 签名类型 与 密钥
                .compressWith(CompressionCodecs.DEFLATE);// 对载荷进行压缩
        if (!CollectionUtils.isEmpty(info)) {
            builder.setClaims(info);
        }
        if (ttlMillis > 0) {
            builder.setExpiration(new Date(System.currentTimeMillis() + ttlMillis));
        }
        if (subject == null) {
            builder.setSubject(issue);
        }
        String compact = builder.compact();
        System.out.println(compact);
        return new CommonResult<>(200, "jwt签发成功", compact);
    }


    public CommonResult parseJWT(String jwtString) {
        try {
            Claims body = Jwts
                    .parser()
//                    .setSigningKey(secretKey)
                    .setSigningKey("QingDaiXYZ")
                    .parseClaimsJws(jwtString)
                    .getBody();
            return new CommonResult(200, "校验成功", body);
        } catch (Exception e) {
            System.out.println(e);
            return new CommonResult(400, "校验失败");
        }
    }

    public CommonResult getUserIdByJwt(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization == null || authorization.isEmpty()) {
            CommonResult<Object> a = new CommonResult<>(400, "未具有令牌");
            String result = JSON.toJSONString(a);
            return a;
        } else {
//                清除jwt前置前缀
            String jwt = authorization.replace("bearer ", "");
            if (jwt.isEmpty()) {
                CommonResult<Object> b = new CommonResult<>(400, "空令牌");
                String result = JSON.toJSONString(b);
                return b;
            } else {
                CommonResult result = this.parseJWT(jwt);
                if (result.getCode() == 200) {
                    String a = StringUtils.substringBetween(result.getData().toString(), "userId=", ",");
                    String b = StringUtils.substringBetween(result.getData().toString(), "userId=", "}");
                    String userIdString = a != null ? a : b;
                    Integer userId = Integer.valueOf(userIdString);
                    return new CommonResult<>(200,"根据令牌获取userId成功",userId);
                }else {
                    return new CommonResult<>(400,"令牌非法或过期");
                }
            }
        }

    }


}
